package com.ego.coupon.scheduled;

import com.ego.common.constant.CouponConstant;
import com.ego.coupon.service.SeckillService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @program: ego
 * @description: 商品秒杀定时任务
 * @author: KamTang
 * @create: 2022-12-30 15:53
 **/
@Service
@Slf4j
public class SeckillSkuScheduled {

    @Autowired
    private SeckillService seckillService;
    @Autowired
    private RedissonClient redissonClient;

    /**
     * 利用Redis提供的锁保证幂等性
     * 秒杀商品的定时上架
     * 每天晚上3点
     */
    @Scheduled(cron = "*/3 * * * * ?")
    public void uploadSeckillSku() {
        RLock lock = redissonClient.getLock(CouponConstant.SECKILL_SKU_UPLOAD_LOCK);
        lock.lock(5, TimeUnit.SECONDS);
        try {
            seckillService.uploadSeckillSku();
        } finally {
            lock.unlock();
        }
    }
}
